﻿using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System;
using System.Management;

namespace ExamCommon
{
    public class NetHelper
    {
        /// <summary>
        /// 获取所有本机ipv4地址
        /// </summary>
        /// <returns></returns>
        public static string GetAllIP()
        {
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            string AllIP = string.Empty;
            foreach (IPAddress ip in ips)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    AllIP += string.Empty.Equals(AllIP) ? ip.ToString() : " / " + ip.ToString();
                }
            }
            Console.WriteLine("所有网卡ipv4地址: " + AllIP);
            return AllIP;
        }

        /// <summary>
        /// 获取本机ipv4地址(随机的)
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIp()
        {
            string ipStr = string.Empty;
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            int count = ips.Length;
            for (int i = count - 1; i > 0; i--)
            {
                if (ips[i].AddressFamily == AddressFamily.InterNetwork)
                {
                    ipStr = ips[i].ToString();
                    break;
                }
            }
            return ipStr;
        }

        //TODO 过滤虚拟网卡等非真实网卡， 还未完善
        public string GetFifterIP()
        {
            string ipStr = string.Empty;
            //获取所有网卡信息
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                //Wireless80211         无线网卡;
                //Ppp                   宽带连接;
                //Ethernet              以太网卡;

                //判断是否为可用的以太网卡
                if (adapter.OperationalStatus == OperationalStatus.Up && adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    //获取以太网卡网络接口信息
                    IPInterfaceProperties ip = adapter.GetIPProperties();
                    //获取单播地址集
                    UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                    foreach (UnicastIPAddressInformation ipadd in ipCollection)
                    {
                        if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            ipStr = ipadd.Address.ToString();//获取以太网ip
                            break;
                        }
                    }
                }
                // 判断是否是可用的无线网卡
                else if (adapter.OperationalStatus == OperationalStatus.Up && adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                {
                    //获取以太网卡网络接口信息
                    IPInterfaceProperties ip = adapter.GetIPProperties();
                    //获取单播地址集
                    UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                    foreach (UnicastIPAddressInformation ipadd in ipCollection)
                    {
                        if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            ipStr = ipadd.Address.ToString();//获取无线网卡ip
                            break;
                        }
                    }
                }
                if (!string.Empty.Equals(ipStr))
                {
                    break;
                }
            }
            return ipStr;
        }

        /// <summary>
        /// 获取真实物理网卡ip地址
        /// </summary>
        public static string GetPhysicalIP()
        {
            string ipstr = string.Empty;
            List<string> listIP = new List<string>();
            ManagementClass mcNetworkAdapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc_NetworkAdapterConfig = mcNetworkAdapterConfig.GetInstances();
            foreach (ManagementObject mo in moc_NetworkAdapterConfig)
            {
                string mServiceName = mo["ServiceName"] as string;

                //过滤不可用的网卡  
                if (!(bool)mo["IPEnabled"])
                {
                    continue;
                }

                //过滤虚拟网卡
                if (mServiceName.ToLower().Contains("vmnetadapter")
                 || mServiceName.ToLower().Contains("vmware")
                 || mServiceName.ToLower().Contains("ppoe")
                 || mServiceName.ToLower().Contains("bthpan")
                 || mServiceName.ToLower().Contains("tapvpn")
                 || mServiceName.ToLower().Contains("ndisip")
                 || mServiceName.ToLower().Contains("sinforvnic"))
                {
                    continue;
                }

                string[] mIPAddress = mo["IPAddress"] as string[];  //ip地址
                //bool mDHCPEnabled = (bool)mo["IPEnabled"];//是否开启了DHCP  
                //string mCaption = mo["Caption"] as string;  
                //string mMACAddress = mo["MACAddress"] as string;  
                //string[] mIPSubnet = mo["IPSubnet"] as string[];  
                //string[] mDefaultIPGateway = mo["DefaultIPGateway"] as string[];  
                //string[] mDNSServerSearchOrder = mo["DNSServerSearchOrder"] as string[];  

                if (mIPAddress != null)
                {
                    foreach (string ip in mIPAddress)
                    {
                        // 排除本地环回和ipv6地址 【ipv6时冒分16进制】
                        if (ip != "0.0.0.0" && ip != "127.0.0.1" && !ip.Contains(":"))
                        {
                            listIP.Add(ip);
                        }
                    }
                }
                mo.Dispose();
            }

            foreach (string item in listIP)
            {
                ipstr += string.Empty.Equals(ipstr) ? item : " / " + item;
            }
            Console.WriteLine("物理网卡ipv4地址: " + ipstr);
            return ipstr;
        }
    }
}
